package com.csdj.server.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.csdj.server.pojo.MailConstants;
import com.csdj.server.pojo.MailLog;
import com.csdj.server.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author zyq
 * @Date 2023/2/3 9:37
 * @ClassName: RabbitMQConfig
 * @Description: TODO
 * @Version 1.0
 */
@Configuration
public class RabbitMQConfig {
    private static final Logger logger=
            LoggerFactory.getLogger(RabbitMQConfig.class);
    //缓存的连接工厂
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private IMailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate =
                new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调
         * data:消息唯一标识
         * ack：确认结果
         * cause 失败原因
         */
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            String msgId = data.getId();
            if(ack){
                //如果消息 已被 确认 消息发送成功
                logger.info("{}=========>消息发送成功"+msgId);
                mailLogService.update(new UpdateWrapper<MailLog>()
                .set("status",1).eq("msgId",msgId));
            }else {
                logger.info("{}=========>消息发送失败");
            }
        });

        /**
         * 消息发送失败的回调
         * msg 消息
         * repCode: 响应码
         * repText: 响应内容
         * exchange: 交换机
         * routingkey:路由
         */
        rabbitTemplate.setReturnCallback((msg,repCode,repText,
                                          exchange,routingkey)->{
            logger.info("{}===========>消息发送到queue失败"+msg.getBody());
        });

        return rabbitTemplate;
    }


    /**
     * 队列
     * @return
     */
    @Bean
    public Queue queue(){

        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    /**
     * 交换机
     * @return
     */
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    /**
     * 将队列 绑定到 交换机上 以及路由加载
     * @return
     */
    @Bean
    public Binding binding(){

        return BindingBuilder.bind(queue()).to(directExchange())
                .with(MailConstants.MAIL_ROUTINGKEY_NAME);
    }


}
